package com.guyan.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.guyan.entity.User;
import com.guyan.vo.ResultVo;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * ClassName： LoginInterceptor
 * Date： 2021/6/16 21:05
 *
 * @author 孤焰
 * @version 1.0
 **/

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            Method method = handlerMethod.getMethod();

            ResponseBody responseBody = method.getDeclaredAnnotation(ResponseBody.class);

            if (responseBody != null) {
                response.setContentType("application/json;charset=utf-8");
                ResultVo resultVo = ResultVo.error(5003, "未登录");

                ObjectMapper objectMapper = new ObjectMapper();
                String jsonText = objectMapper.writeValueAsString(resultVo);

                PrintWriter out = response.getWriter();
                out.print(jsonText);
                out.close();
            } else {
                response.sendRedirect(request.getServletContext().getContextPath() + "/user/loginPage");
            }

            return false;
        }

        return true;
    }
}
